package com.cafe.case4;

import org.springframework.util.StopWatch;

import java.util.List;
import java.util.function.IntFunction;
import java.util.stream.IntStream;

public class ThreadCompare {

    /**
     * 创建1万个物理线程
     *
     * @throws InterruptedException
     */
    private static void testPlatformThread() throws InterruptedException {
        List<Thread> platformThreadList = IntStream.range(0, 1_0000).mapToObj(new IntFunction<Thread>() {
            @Override
            public Thread apply(int value) {
                return new Thread(new CafeRunnable());
            }
        }).toList();
        StopWatch stopWatch = new StopWatch("计时器");
        stopWatch.start("传统线程");
        for (Thread thread : platformThreadList) {
            thread.start();
            thread.join();
        }
        stopWatch.stop();
        System.out.println(stopWatch.getLastTaskName() + "耗时：\t" + stopWatch.getLastTaskTimeMillis() + "ms");
    }

    /**
     * 创建1万个虚拟线程
     *
     * @throws InterruptedException
     */
    private static void testVirtualThread() throws InterruptedException {
        List<Thread> virtualThreadList = IntStream.range(0, 1_0000).mapToObj(new IntFunction<Thread>() {
            @Override
            public Thread apply(int value) {
                return Thread.ofVirtual().unstarted(new CafeRunnable());
            }
        }).toList();
        StopWatch stopWatch = new StopWatch("计时器");
        stopWatch.start("虚拟线程");
        for (Thread thread : virtualThreadList) {
            thread.start();
            thread.join();
        }
        stopWatch.stop();
        System.out.println(stopWatch.getLastTaskName() + "耗时：\t" + stopWatch.getLastTaskTimeMillis() + "ms");
    }


    public static void main(String[] args) throws InterruptedException {
        testVirtualThread();
    }
}
